//
//  TKUtil.m
//  Trackit
//
//  Created by yaodaobin on 2017/4/2.
//  Copyright © 2017年 yaodaobin. All rights reserved.
//

#import "TKUtil.h"
#import "Reachability.h"
#import "LPPopup.h"
#import "SBJson.h"
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>


#include "sys/stat.h"
#include <fnmatch.h>
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

#import "NSUserDefaults+UnRegisterDefault.h"
#import "BaseNavigationController.h"
#import "SegmentedControl.h"
#import "UIImage+Color.h"
#import "HandNetWorkErrorUtil.h"
#import "NSDictionary+FilterNull.h"
#import "NSMutableArray+Safe.h"
#import "NSArray+Safe.h"

#define MMBANG_DATA_CACHE @"MMBANG_DATA_CACHE_%@_%@"
#define DEFAULT_VOID_COLOR [UIColor whiteColor]



#define MAX_CACHE_SIZE 1024 * 1024 * 10
#define MIN_CACHE_SIZE 1024 * 1024 * 2     // 超过100M缓存后，自动清理，只留20M
#define kMaskImgTag 3333

static UIWebView *uaWebView = nil;

@implementation TKUtil
+ (void)showMessageFromServer:(id)data defaultMsg:(NSString *)message {
    NSString *msg = message;
    NSString *msgFromServer = [data valueForKey:@"message"];
    if ([msgFromServer isKindOfClass:[NSString class]] && [msgFromServer length]) {
        msg = msgFromServer;
    }
    if ([msg length]) {
        [self showMessage:msg];
    }
}

+ (void)showMessage:(NSString *)message {
    [TKUtil showMessageAlignCenter:message];
}

+ (void)showMessageAlignCenter:(NSString *)message {
    if (message.length == 0) {
        return;
    }
    LPPopup *popup = [LPPopup popupWithText:message];
    
    CGFloat duration = MAX(2.0f, message.length / 12.0f);
    CGFloat offset = 0.0f;
    
    BOOL isNavBarHidden = YES;
    
    if (!isNavBarHidden) {
        offset = 23.0f;
    }
    
    UIWindow *window = [[[UIApplication sharedApplication] windows] objectAtIndex:0];
    [popup showInView:window
        centerAtPoint:CGPointMake(window.center.x, window.center.y + 0 + offset)
             duration:duration
           completion:nil];
    
}

+ (void)showMessage:(NSString *)message withOffset:(CGFloat)offset {
    LPPopup *popup = [LPPopup popupWithText:message];
    
    CGFloat duration = MAX(2.0f, message.length / 12.0f);
    
    UIWindow *window = [[[UIApplication sharedApplication] windows] objectAtIndex:0];
    [popup showInView:window
        centerAtPoint:CGPointMake(window.center.x, window.center.y + 0 + offset)
             duration:duration
           completion:nil];
    //    popup.center = window.center;
    //    [MBProgressHUD LightToolTipWithString:message withOffset:offset];
}
/**
 *  判断是否允许访问相册
 */
+ (BOOL)judgePhotoPerm {
    return YES;    
}

+ (BOOL)isNumberFromString:(NSString *)string {
    if (string == nil) {
        return false;
    }
    
    if ([string isKindOfClass:[NSNumber class]]) {
        return YES;
    }
    
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    return [string isEqualToString:filtered];
}

+ (UIImage *)limiteSizeWithImage:(UIImage *)rawImage {
    CGFloat width = rawImage.size.width;
    CGFloat height = rawImage.size.height;
    
    if (width >= UPLOAD_IMAGE_MIN_SIZE && height >= UPLOAD_IMAGE_MIN_SIZE) {
        return rawImage;
    }
    
    CGFloat scale = UPLOAD_IMAGE_MIN_SIZE / MIN(width, height);
    CGSize newSize = CGSizeMake(width * scale, height * scale);
    
    UIImage *newImage = [TKUtil resizeImageWithRawImage:rawImage scaledToSize:newSize];
    
    return newImage;
}

+ (UIImage *)resizeImageWithRawImage:(UIImage*)image scaledToSize:(CGSize)newSize {
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return resizedImage;
}

+ (UIImage *)restrictImage:(UIImage *)image inSize:(CGFloat)size {
    if (image.size.width <= size && image.size.height <= size) {
        return image;
    }
    
    CGFloat hScale = image.size.width / size;
    CGFloat vScale = image.size.height / size;
    CGFloat scale = MAX(hScale, vScale);
    CGSize newSize = CGSizeMake(image.size.width / scale, image.size.height / scale);
    
    image = [TKUtil resizeImageWithRawImage:image scaledToSize:newSize];
    
    return image;
}

+ (BOOL)writeImage:(UIImage*)image toFileAtPath:(NSString*)aPath {
    if ((image == nil) || (aPath == nil) || ([aPath isEqualToString:@""]))
    return NO;
    
    @try
    {
        NSData *imageData = nil;
        NSString *ext = [aPath pathExtension];
        if ([ext isEqualToString:@"png"]) {
            imageData = UIImagePNGRepresentation(image);
        } else {
            imageData = UIImageJPEGRepresentation(image, 0);
        }
        
        if ((imageData == nil) || ([imageData length] <= 0))
        return NO;
        
        [imageData writeToFile:aPath atomically:YES];
        return YES;
    } @catch (NSException *e) {
    }
    
    return NO;
}

+ (BOOL)isNetworkAvailable {
    NetworkStatus status = [[Reachability reachabilityWithHostName:@"www.baidu.com"] currentReachabilityStatus];
    return status != NotReachable;
}

+ (BOOL)isHostAvailable:(NSString *)hostname {
    NetworkStatus status = [[Reachability reachabilityWithHostName:hostname] currentReachabilityStatus];
    return status != NotReachable;
}


+ (void)showNetworkErrorMsg:(NSError *)error isPop:(BOOL)isPop
{
    if (error) {
        [TKUtil processNetworkErrorMsg:error block:^(NSString *msg) {
            if ([msg isEqualToString:@"网络不太给力哦~"]) {
                //
                if (isPop) {
                    [[HandNetWorkErrorUtil instance] showPopAlterView];
                }
            } else {
                if (isPop) {
                    [TKUtil showMessage:msg];
                }
            }
            
        }];
    }
}

+ (void)processNetworkErrorMsg:(NSError *)error block:(ProcessStringBlock)block {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *msg = [TKUtil getNetworkErrorMsg:error];
        if (block) {
            dispatch_async(dispatch_get_main_queue(), ^{
                block(msg);
            });
        }
    });
}


+ (NSString *)getNetworkErrorMsg:(NSError *)error {
    NSString *msg = @"";
    
    //error code: https://developer.apple.com/library/ios/documentation/Networking/Reference/CFNetworkErrors/Reference/reference.html
    if (error) {
        if (error.code == kCFURLErrorTimedOut) {
            // -1001 连接超时
            msg = @"连接超时";
//            if ([TKUtil isMMbangAvailable]) {
//                msg = MMBANG_NETWORK_ERR_UNSTABLE;
//            } else {
//                msg = MMBANG_NETWORK_ERR_WEINAI;
//            }
        } else if (error.code == kCFURLErrorCannotConnectToHost) {
            // -1004
            BOOL networkAvailable = [TKUtil isNetworkAvailable];
            
            if (networkAvailable) {
                msg = MMBANG_NETWORK_ERR_WEINAI;
            } else {
                msg = MMBANG_NETWORK_ERR_UNSTABLE;
            }
        } else if (error.code == kCFURLErrorBadServerResponse) {
            // -1011 502 bad gateway
            msg = MMBANG_NETWORK_ERR_WEINAI;
        } else {
            // -1009
            msg = MMBANG_NETWORK_ERR_UNSTABLE;
        }
    }
    
    return msg;
}

#pragma mark - 最少返回12像素
+ (CGFloat)heightForText:(NSString*)contentText width:(CGFloat)width font:(UIFont *)font {
    if ([contentText length] == 0) {
        return 12;
    }
    CGSize size = CGSizeZero;
    CGSize rSize = CGSizeMake(width - kTextViewPadding * 2, NSUIntegerMax);
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_7_0
    NSDictionary* attributes = [NSDictionary dictionaryWithObjectsAndKeys: font, NSFontAttributeName, nil];
    CGRect rect = [contentText boundingRectWithSize:rSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
    size = rect.size;
#else
    size=[contentText sizeWithFont:font constrainedToSize:rSize lineBreakMode:0];
#endif
    return size.height + kTextViewPadding * 2;
}

#pragma mark - 根据字体，宽度返回 高度
+ (CGFloat)heightWithText:(NSString *)text font:(UIFont *)font width:(CGFloat)width minHeight:(CGFloat)minHeight {
    if (text) {
        CGSize size = CGSizeZero;
        CGSize rSize = CGSizeMake(width, NSUIntegerMax);
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_7_0
        NSDictionary* attributes = [NSDictionary dictionaryWithObjectsAndKeys: font, NSFontAttributeName, nil];
        CGRect rect = [text boundingRectWithSize:rSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
        size = rect.size;
#else
        size = [text sizeWithFont:font constrainedToSize:rSize];
#endif
        if (size.height > minHeight) {
            return size.height;
        } else {
            return minHeight;
        }
    }
    
    return minHeight;
}

+ (CGSize)sizeWithText:(NSString *)text boundingSize:(CGSize)boundingSize font:(UIFont *)font lineBreakMode:(NSLineBreakMode)lineBreakMode {
    CGSize textSize;
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_7_0
    CGRect rect = [text boundingRectWithSize:boundingSize
                                     options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine
                                  attributes:[NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName]
                                     context:nil];
    textSize        = rect.size;
    textSize.width  = ceil(textSize.width);
    textSize.height = ceil(textSize.height);
    
#else
    // -boundingRectWithSize:options:attributes:context: is available in iOS 7.0 and later
    if ( [text respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)] ) {
        CGRect rect = [text boundingRectWithSize:boundingSize
                                         options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine
                                      attributes:[NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName]
                                         context:nil];
        textSize        = rect.size;
        textSize.width  = ceil(textSize.width);
        textSize.height = ceil(textSize.height);
        
    }else{
        
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        textSize = [text sizeWithFont:font constrainedToSize:boundingSize lineBreakMode:lineBreakMode];
        textSize.width  = ceil(textSize.width);
        textSize.height = ceil(textSize.height);
#pragma clang diagnostic pop
        
    }
#endif
    return textSize;
}

+ (CGFloat)heightWithText:(NSString *)text boundingSize:(CGSize)boundingSize font:(UIFont *)font lineBreakMode:(NSLineBreakMode)lineBreakMode {
    CGSize size = [self sizeWithText:text boundingSize:boundingSize font:font lineBreakMode:lineBreakMode];
    return size.height;
}

+ (CGFloat)widthWithText:(NSString *)text font:(UIFont *)font height:(CGFloat)height minWidth:(CGFloat)minWidth {
    if (text) {
        CGSize size = CGSizeZero;
        CGSize rSize = CGSizeMake(NSUIntegerMax, height);
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_7_0
        NSDictionary* attributes = [NSDictionary dictionaryWithObjectsAndKeys: font, NSFontAttributeName, nil];
        CGRect rect = [text boundingRectWithSize:rSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
        size = rect.size;
#else
        size = [text sizeWithFont:font constrainedToSize:rSize];
#endif
        if (size.width > minWidth) {
            return size.width;
        } else {
            return minWidth;
        }
    }
    return minWidth;
}


+ (CGFloat)getFontSpaceWithLabel:(UIFont *)font {
    CGFloat space =  round(font.lineHeight - font.pointSize)/2.;
    return space;
}

+ (UIImage *)createImageFromColor:(UIColor *)color withSize:(CGSize)size {
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

+ (UIImage *)createImageFromColor:(UIColor *)color {
    return [self createImageFromColor:color withSize:CGSizeMake(1, 1)];
}

+ (NSString *)trimWhitespace:(NSString *)string {
    NSMutableString *str = [string mutableCopy];
    CFStringTrimWhitespace((__bridge CFMutableStringRef)str);
    
    return str;
}

+ (UIViewAnimationOptions)animationOptionsForCurve:(UIViewAnimationCurve)curve {
    switch (curve) {
        case UIViewAnimationCurveEaseInOut:
        return UIViewAnimationOptionCurveEaseInOut;
        break;
        case UIViewAnimationCurveEaseIn:
        return UIViewAnimationOptionCurveEaseIn;
        break;
        case UIViewAnimationCurveEaseOut:
        return UIViewAnimationOptionCurveEaseOut;
        break;
        case UIViewAnimationCurveLinear:
        return UIViewAnimationOptionCurveLinear;
        break;
    }
    
    return kNilOptions;
}

+ (UIImage*)convertImageToGreyScale:(UIImage*)image {
    // Create image rectangle with current image width/height
    CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height);
    
    // Grayscale color space
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    
    // Create bitmap content with current image size and grayscale colorspace
    CGContextRef context = CGBitmapContextCreate(nil, image.size.width, image.size.height, 8, 0, colorSpace, kCGImageAlphaNone);
    
    // Draw image into current context, with specified rectangle
    // using previously defined context (with grayscale colorspace)
    CGContextDrawImage(context, imageRect, [image CGImage]);
    
    // Create bitmap image info from pixel data in current context
    CGImageRef imageRef = CGBitmapContextCreateImage(context);
    
    // Create a new UIImage object
    UIImage *newImage = [UIImage imageWithCGImage:imageRef];
    
    // Release colorspace, context and bitmap information
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);
    CFRelease(imageRef);
    
    // Return the new grayscale image
    return newImage;
}

#pragma mark 路径，存储
+ (NSURL *)getApplicationDocumentsDirectory {
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

+ (NSString *)getDocumentPath:(NSString *)lastFolderName {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    documentsDirectory = [documentsDirectory stringByAppendingPathComponent:lastFolderName];
    
    return documentsDirectory;
}

+ (NSString *)getUserDocumentPath:(NSString *)lastFolderName {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    NSString *userPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",APP_DELEGATE.user.userID]];
    NSString *filePath = [userPath stringByAppendingPathComponent:lastFolderName];
    return filePath;
}

#pragma mark - 存储数据
+ (void)saveDataWithKey:(NSString *)key ofValue:(id)value {
    NSString *k = [NSString stringWithFormat:MMBANG_DATA_CACHE, @"", key];
    if ([value isKindOfClass:[NSDictionary class]]) {
        value = [value deleteAllNullValue];
    } else if ([value isKindOfClass:[NSMutableDictionary class]]) {
        NSLog(@"1134");
    }
    [[NSUserDefaults standardUserDefaults] setObject:value forKey:k];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (void)clearDataWithKey:(NSString *)key {
    NSString *k = [NSString stringWithFormat:MMBANG_DATA_CACHE, @"", key];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:k];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (id)getDataWithKey:(NSString *)key
{
    NSString *k = [NSString stringWithFormat:MMBANG_DATA_CACHE, @"", key];
    return [[NSUserDefaults standardUserDefaults] objectForKey:k];
}

+ (void)saveEntityWithKey:(NSString *)key ofValue:(id)value {
    NSData *entity = [NSKeyedArchiver archivedDataWithRootObject:value];
    
    [self saveDataWithKey:key ofValue:entity];
}

+ (id)getEntityWithKey:(NSString *)key {
    NSData *entity = [self getDataWithKey:key];
    
    return [NSKeyedUnarchiver unarchiveObjectWithData:entity];
}

+ (void)saveLoginUserInfo:(User *)user {

}

+ (User *)getLoginUserInfo {
    User *user = [[User alloc] init];

    return user;
}

+ (void)clearLoginUserInfo {
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"WeiboAuthData"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"QQAuthData"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [self saveDataWithKey:@"userID" ofValue:nil];
    [self saveDataWithKey:@"isGuset" ofValue:[NSNumber numberWithBool:YES]];
}

+ (BOOL)hasReadedGuide {
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSNumber *readed = [TKUtil getDataWithKey:[NSString stringWithFormat:@"guide%@", version]];
    
    return readed && readed.boolValue == YES;
}

+ (void)readGuide {
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    [TKUtil saveDataWithKey:[NSString stringWithFormat:@"guide%@", version] ofValue:[NSNumber numberWithBool:YES]];
}

// 这个字段好像不会被清除掉，暂时用这个做为判断依据
+ (BOOL)isOldUser{
    id isGuest = [self getDataWithKey:@"isGuset"];
    if (isGuest != nil) {
        return YES;
    }
    return NO;
}

#pragma mark 存储 O2O 景区信息
/**
 *  返回所有城市的 景区信息
 *
 *  @return dictionary
 */
+ (NSDictionary *)getO2OAllScenices {
    NSString *path = [self getDocumentPath:@"O2OScenicZones.plist"];
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
    
    return dic;
}

+ (NSDictionary *)getO2OScenicDataWithCityID:(NSString *)cityID {
    NSString *path = [self getDocumentPath:@"O2OScenicZones.plist"];
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
    
    NSDictionary *scenic = dic[cityID];
    return scenic;
}

/**
 *  存储 足迹里面的景区信息，以里面的_id(城市id)直接存储
 *
 *  @param dictionary 从服务器拉回来的数据，
 *
 *  @return 是否存储成功
 */
+ (BOOL)saveO2OScenicData:(NSDictionary *)dictionary {
    if (!dictionary) {
        return NO;
    }
    
    NSString *path = [self getDocumentPath:@"O2OScenicZones.plist"];
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
    NSMutableDictionary *mutDic = [NSMutableDictionary dictionaryWithCapacity:0];
    if (dic && [dic isKindOfClass:[NSDictionary class]]) {
        [mutDic setDictionary:dic];
    }
    // 删除 用户的 footprints
    NSMutableDictionary *mutScenic = [dictionary mutableCopy];
    [mutScenic removeObjectForKey:@"footprints"];
    
    int ID = [dictionary[@"_id"] intValue];
    [mutDic setObject:mutScenic forKey:[NSString stringWithFormat:@"%d",ID]];
    
    return [mutDic writeToFile:path atomically:YES];
}

#pragma mark - 存储 位置搜索的历史记录
+ (NSArray *)getO2OLocationSearchHistory {
    NSString *path = [self getDocumentPath:@"O2OLocationSearchHistory.plist"];
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
    NSArray *arr = [dic objectForKey:@"items"];
    return arr;
}

+ (BOOL)saveO2OLocationSearchHistory:(NSDictionary *)dictionary {
    if (!dictionary) {
        return NO;
    }
    
    NSString *path = [self getDocumentPath:@"O2OLocationSearchHistory.plist"];
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
    NSMutableDictionary *mutDic = [NSMutableDictionary dictionaryWithCapacity:0];
    if (dic && [dic isKindOfClass:[NSDictionary class]]) {
        [mutDic setDictionary:dic];
    }
    NSMutableArray *arr = [mutDic[@"items"] mutableCopy];
    if (!arr) {
        arr = [NSMutableArray array];
    }
    
    BOOL isExit = NO;
    for (int i = 0; i<arr.count; i++) {
        NSDictionary *loc = arr[i];
        if ([loc isEqualToDictionary:dictionary]) {
            isExit = YES;
            [arr exchangeObjectAtIndex:i withObjectAtIndex:0];
            break;
        }
    }
    if (!isExit) {
        [arr insertObject:dictionary atIndex:0];
    }
    [mutDic setObject:arr forKey:@"items"];
    
    return [mutDic writeToFile:path atomically:YES];
}

+ (BOOL)cleanO2OLocationSearchHistory {
    NSString *path = [self getDocumentPath:@"O2OLocationSearchHistory.plist"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        return [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
    }
    return YES;
}

#pragma mark -
+ (NSString *)jsonStringWithObject:(id)object {
    SBJsonWriter *writer = [[SBJsonWriter alloc] init];
    
    return [writer stringWithObject:object];
}

+ (BOOL)isEqualFromString:(NSString *)from toString:(NSString *)toString {
    return [[NSString stringWithFormat:@"%@", from] isEqualToString:[NSString stringWithFormat:@"%@", toString]];
}

+ (NSArray *)splitString:(NSString *)rawString withMaxLength:(NSInteger)maxLength {
    if (rawString.length < maxLength) {
        return [NSArray arrayWithObject:rawString];
    }
    NSMutableArray *splitedStringArray = [[NSMutableArray alloc] init];
    for (int i = 0 ; i < rawString.length / maxLength + 1 ; i++) {
        [splitedStringArray addObject:[rawString substringWithRange:NSMakeRange(i * maxLength, MIN((i + 1) * maxLength, rawString.length - i * maxLength))]];
    }
    
    return splitedStringArray;
}

//mac address
// Return the local MAC addy
// Courtesy of FreeBSD hackers email list
// Accidentally munged during previous update. Fixed thanks to erica sadun & mlamb.
+ (NSString *)macAddress {
    int                 mib[6];
    size_t              len;
    char                *buf;
    unsigned char       *ptr;
    struct if_msghdr    *ifm;
    struct sockaddr_dl  *sdl;
    
    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;
    
    if ((mib[5] = if_nametoindex("en0")) == 0) {
        printf("Error: if_nametoindex error\n");
        return NULL;
    }
    
    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 1\n");
        return NULL;
    }
    
    if ((buf = malloc(len)) == NULL) {
        printf("Could not allocate memory. error!\n");
        return NULL;
    }
    
    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 2");
        free(buf);
        return NULL;
    }
    
    ifm = (struct if_msghdr *)buf;
    sdl = (struct sockaddr_dl *)(ifm + 1);
    ptr = (unsigned char *)LLADDR(sdl);
    NSString *outstring = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
                           *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    free(buf);
    
    return outstring;
}

//add li
BOOL isValidatePhone(NSString * candidate) {
    //    NSString *phoneRegex = @"(13[0-9]|15[0|3|6|7|8|9]|18[2|3|6|7|8|9])\\d{8}";
    NSString *phoneRegex=@"(\\d{11,11})";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    
    return [phoneTest evaluateWithObject:candidate];
}

BOOL isValidateEmail(NSString * candidate) {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    
    return [emailTest evaluateWithObject:candidate];
}

UIColor * colorWithHexString(NSString *stringToConvert) {
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    if ([cString length] < 6)
    return DEFAULT_VOID_COLOR;
    if ([cString hasPrefix:@"#"])
    cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
    return DEFAULT_VOID_COLOR;
    
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}

NSString* getBabyGenerType(NSString *string) {
    if (string.length == 0) {
        return nil;
    } else {
        NSArray *array = [[NSArray alloc]initWithObjects:@"不知道性别", @"男孩", @"女孩", @"双胞胎兄弟", @"双胞胎姐妹", @"龙凤胎", @"多胞胎", nil];
        NSInteger i = [array indexOfObject:string];
        return [NSString stringWithFormat:@"%@",@(i+1)];
    }
}

void setExclusiveTouchToChildrenOf(NSArray *subviews) {
    for (UIView *v in subviews) {
        setExclusiveTouchToChildrenOf(v.subviews);
        if ([v isKindOfClass:[UIButton class]]) {
            UIButton *btn = (UIButton *)v;
            [btn setExclusiveTouch:YES];
        }
    }
}



#pragma mark -- createFilePath

+ (NSString *)folderPath:(NSString*)folderPath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *newFilePath = [paths[0] stringByAppendingPathComponent:folderPath];
    return newFilePath;
}

+ (NSString *)createFolderPathIfNeeded:(NSString *)folderPath {
    BOOL pathExists = NO;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *newFolderPath = [paths[0] stringByAppendingPathComponent:folderPath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if (![fileManager fileExistsAtPath:newFolderPath]) {
        [fileManager createDirectoryAtPath:newFolderPath withIntermediateDirectories:YES attributes:nil error:NULL];
        pathExists = [fileManager fileExistsAtPath:newFolderPath];
    } else {
        pathExists = YES;
    }
    
    return pathExists ? newFolderPath : nil;
}


+ (void)cleanFolderPath:(NSString*)folderPath {
    dispatch_queue_t removeOtherCacheQueue = dispatch_queue_create("removeOtherCache", DISPATCH_QUEUE_SERIAL);
    dispatch_async(removeOtherCacheQueue, ^ {
        [[NSFileManager defaultManager] removeItemAtPath:[self folderPath:folderPath] error:nil];
        [self createFolderPathIfNeeded:folderPath];
    });
}

BOOL getFileName(NSString *fileName) {
    NSFileManager *fm = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *plistPath1 = [paths objectAtIndex:0];
    //得到完整的文件名
    NSString *filename=[plistPath1 stringByAppendingPathComponent:fileName];
    
    return [fm fileExistsAtPath:filename];
    
}

void removePlist(NSString *strPlistName) {
    NSFileManager *fm = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *plistPath1 = [paths objectAtIndex:0];
    
    //得到完整的文件名
    NSString *filename=[plistPath1 stringByAppendingPathComponent:strPlistName];
    if ([fm fileExistsAtPath:filename]) {
        NSError *error;
        BOOL isDelete = [fm removeItemAtPath:filename error:&error];
        NSLog(@"%d",isDelete);
    }
}

//创建文件
NSString * getPlistName(NSString *strPlistName) {
    NSFileManager *fm = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *plistPath1 = [paths objectAtIndex:0];
    //得到完整的文件名
    NSString *filename=[plistPath1 stringByAppendingPathComponent:strPlistName];
    if (![fm fileExistsAtPath:filename])
    {
        [fm createFileAtPath:filename contents:nil attributes:nil];
    }
    return filename;
}

void writeToPlist(NSString *strPlistName, NSData *arrData) {
    [arrData writeToFile:getPlistName(strPlistName) atomically:YES];
    
}

#pragma mark - UIWebView UserAgent

+ (void)registerUIWebViewUserAgent {
    NSString *originUserAgent = [self originUIWebViewUserAgent];
    
    NSString *mmbangVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *modifiedUserAgent = [NSString stringWithFormat:@"%@ mmbang/%@ NetType/%@",originUserAgent,mmbangVersion,[self dataNetworkTypeFromStatusBar]];
    
    NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:modifiedUserAgent, @"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
    
}

+ (void)unregisterUIWebViewUserAgent {
    [[NSUserDefaults standardUserDefaults] unregisterDefaultForKey:@"UserAgent"];
}

+ (NSString *)originUIWebViewUserAgent {
    if (!uaWebView) {
        uaWebView = [UIWebView new];
    }
    NSString* secretAgent = [uaWebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    return secretAgent;
}

// UITextField Limit Max Lenght

+ (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string limitMaxLength:(NSUInteger)maxLength {
    NSString *shouldText = [textField.text stringByReplacingCharactersInRange:range withString:string];
    NSInteger strLength = shouldText.length;
    if (strLength > maxLength) {
        // 允许删除
        if (strLength < textField.text.length) {
            return YES;
        }
        // 已经超长了，不允许输入更多
        return NO;
    }
    return YES;
}

+ (void)saveUserInfoWithServerData:(NSDictionary *)data dismissLoginNav:(BOOL)dismiss {
    User *user = [[User alloc] initWithData:[data valueForKeyPath:@"data"]];
    [TKUtil saveDataWithKey:@"userInfo" ofValue:[data valueForKeyPath:@"data"]];
    APP_DELEGATE.user = user;
    [TKUtil saveLoginUserInfo:user];
    [[NSNotificationCenter defaultCenter] postNotificationName:kLoginSuccessNotification object:nil];
    
    if (dismiss) {
        [APP_DELEGATE.loginNavController dismissWithCompletion:^{
            APP_DELEGATE.loginNavController = nil;
        }];
    }
}

+ (NSString *)appName {
    return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"];
}

#pragma mark -
#pragma mark 判断字符串是否为空（nil和length为0都是空）

+ (BOOL)isEmpty:(NSString *)value {
    return  (nil == value || [value isKindOfClass:[NSNull class]] || ([value length] == 0) || [[value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] isEqualToString:@""]);
}

+ (NSString *)getScreenSize {
    if (kScreenFrame.size.width == 320) {
        return @"m";
    } else if (kScreenFrame.size.width == 375) {
        return @"l";
    } else if (kScreenFrame.size.width == 414) {
        return @"xx";
    } else {
        return @"m";
    }
    
}

+ (void)updateSysUserInfo:(User *)user {
    APP_DELEGATE.user = user;
}

+ (UILabel *)createLabel:(UIFont *)textFont color:(UIColor *)textColor {
    UILabel *label = [[UILabel alloc] init];
    label.textColor = textColor;
    label.backgroundColor = [UIColor clearColor];
    label.font = textFont;
    return label;
}

+ (UILabel *)creatSizeFitLabelWithFont:(UIFont *)font color:(UIColor *)color superView:(UIView *)superView {
    UILabel *label = [[UILabel alloc] init];
    [label setFont:font];
    [label setTextColor:color];
    label.backgroundColor = [UIColor clearColor];
    [superView addSubview:label];
    [label sizeToFit];
    return label;
}
/**
 *  格式化距离，如果小于1000米，则单位返回 ***米，否则返回 ****公里
 *
 *  @param meters 需要格式化的 距离，单位为米
 *
 *  @return 格式化后的字符串
 */
+ (NSString *)formatDistanceWithMeters:(double)meters {
    if (meters < 1000) {
        NSString *result = [NSString stringWithFormat:@"%g米",meters];
        return result;
    } else {
        NSString *result = [NSString stringWithFormat:@"%.1f公里",meters/1000.0];
        return result;
    }
}
//textview 上下左右各有8＊px 距离

+ (float) heightForTextView: (UITextView *)textView WithText: (NSString *) strText {
    float fPadding = 16.0; // 8.0px x 2
    //    CGSize constraint = CGSizeMake(textView.contentSize.width - fPadding, CGFLOAT_MAX);
    CGSize rSize = CGSizeMake(textView.contentSize.width - fPadding, NSUIntegerMax);
    CGSize size = CGSizeZero;
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_7_0
    NSDictionary* attributes = [NSDictionary dictionaryWithObjectsAndKeys: textView.font, NSFontAttributeName, nil];
    CGRect rect = [strText boundingRectWithSize:rSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
    size = rect.size;
#else
    size = [strText sizeWithFont: textView.font constrainedToSize:rSize lineBreakMode:UILineBreakModeWordWrap];
#endif
    
    float fHeight = size.height + 16.0;
    
    return fHeight;
}

/**
 *  从cover字典里取根据屏幕尺寸匹配的image url
 *
 *  @param dict cover字典
 *
 *  @return 正确的image url
 */

+ (NSString *)preferedImageFromImagesDict:(NSDictionary *)dict {
    if ([dict isKindOfClass:[NSString class]]) {
        return (NSString *)dict;
    }
    NSString *string = @"";
    string = [dict objectForKey:[TKUtil getScreenSize]];
    return string;
}

+ (UIImage *)createDefaultImage:(NSString *)defaultImageName InView:(UIView *)parentView {
    
    UIImage *image = [self createDefaultImage:defaultImageName withSize:parentView.frame.size];
    return image;
}

+ (UIImage *)createDefaultO2OImageInView:(UIView *)parentView {
    UIImage *image = [self createDefaultImage:kDefaultO2OImage InView:parentView];
    return image;
}

+ (UIImage *)createDefaultImage:(NSString *)defaultImageName withSize:(CGSize)size {
    UIImage *cacheIm = [[SDImageCache sharedImageCache] imageFromMemoryCacheForKey:[[NSMutableString alloc] initWithFormat:@"%@Width_%@Height_%@",defaultImageName,@(size.width),@(size.height)]];
    if (cacheIm) {
        return cacheIm;
    }
    UIImage *image = [UIImage imageNamed:defaultImageName];
    CGFloat width = size.width;
    CGFloat height = size.height;
    
    //suppose image is square.
    NSAssert(fabs(image.size.width - image.size.height) < 2, @"default image is squre. It's a minor request, please obey");
    
    CGFloat minWidth = MIN(width, height);
    CGFloat imgWidth = image.size.width;
    if (minWidth < 108) {
        imgWidth = imgWidth*minWidth/108.;
    }
    //    if (minWidth < imgWidth) {
    //        imgWidth = minWidth * 3 / 4;
    //    }
    
    CGRect imgFrame = CGRectMake((width - imgWidth) / 2, (height - imgWidth) / 2, imgWidth, imgWidth);
    
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIColor *color = [UIColor colorWithHex:0xf5f5f5 alpha:1];
    UIGraphicsBeginImageContextWithOptions(rect.size, YES, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    [image drawInRect:imgFrame];
    image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [[SDImageCache sharedImageCache] storeImage:image forKey:[[NSMutableString alloc] initWithFormat:@"%@Width_%@Height_%@",defaultImageName,@(size.width),@(size.height)] toDisk:NO];
    return image;
}


+ (NSString *)folderSizeAtPath:(NSString *)path {
    
    const char* folderPath = [path cStringUsingEncoding:NSUTF8StringEncoding];
    long long folderSize = 0;
    DIR* dir = opendir(folderPath);
    if (dir == NULL) return 0;
    struct dirent* child;
    while ((child = readdir(dir)) != NULL) {
        
        if (child->d_type == DT_DIR && (
                                        (child->d_name[0] == '.' && child->d_name[1] == 0) || // 忽略目录 .
                                        (child->d_name[0] == '.' && child->d_name[1] == '.' && child->d_name[2] == 0) // 忽略目录 ..
                                        )) continue;
        
        unsigned long folderPathLength = strlen(folderPath);
        
        char childPath[1024]; // 子文件的路径地址
        
        stpcpy(childPath, folderPath);
        
        if (folderPath[folderPathLength-1] != '/'){
            childPath[folderPathLength] = '/';
            folderPathLength++;
        }
        
        stpcpy(childPath+folderPathLength, child->d_name);
        
        if (child->d_type == DT_REG || child->d_type == DT_LNK){ // file or link
            struct stat st;
            if(lstat(childPath, &st) == 0) folderSize += st.st_size;
        }
    }
    closedir(dir);
    NSString *sizeString = [NSString stringWithFormat:@"%.1fM",folderSize/(1024.0*1024.0)];
    return sizeString;
}

//是否支持手势滑动，popViewController
+ (void)isCanDragBack:(BOOL)isBack {
    APP_DELEGATE.navController.canDragBackInMainView = isBack;
    APP_DELEGATE.navController.canDragBack = isBack;
    if ([APP_DELEGATE.navController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        APP_DELEGATE.navController.interactivePopGestureRecognizer.enabled = isBack;
    }
}

+ (BOOL)emptyOrNull:(NSString *)str {
    return str == nil || (NSNull *)str == [NSNull null] || str.length == 0 ;
}

#pragma mark - 生成 UUID
+ (NSString *)createUUID {
    // generate a new uuid and store it in user defaults
    CFUUIDRef uuid = CFUUIDCreate(NULL);
    NSString *uuID = (NSString *) CFBridgingRelease(CFUUIDCreateString(NULL, uuid));
    CFRelease(uuid);
    
    return uuID;
}

#pragma mark - device Model

+ (NSString *)deviceModelOrigin {
    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *machine = (char*)malloc(size);
    sysctlbyname("hw.machine", machine, &size, NULL, 0);
    NSString *platform = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
    free(machine);
    return platform;
}

+ (NSString *)deviceModel {
    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *machine = (char*)malloc(size);
    sysctlbyname("hw.machine", machine, &size, NULL, 0);
    NSString *platform = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
    free(machine);
    
    //http://blog.csdn.net/xufeidll/article/details/24306187
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G (A1203)";
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G (A1241/A1324)";
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS (A1303/A1325)";
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4 (A1332)";
    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4 (A1332)";
    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4 (A1349)";
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S (A1387/A1431)";
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5 (A1428)";
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5 (A1429/A1442)";
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c (A1456/A1532)";
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c (A1507/A1516/A1526/A1529)";
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s (A1453/A1533)";
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s (A1457/A1518/A1528/A1530)";
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus (A1522/A1524)";
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6 (A1549/A1586)";
    if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s Plus (A1687/A1699)";
    if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s (A1688/A1700)";
    
    if ([platform isEqualToString:@"iPod1,1"])   return @"iPod Touch 1G (A1213)";
    if ([platform isEqualToString:@"iPod2,1"])   return @"iPod Touch 2G (A1288)";
    if ([platform isEqualToString:@"iPod3,1"])   return @"iPod Touch 3G (A1318)";
    if ([platform isEqualToString:@"iPod4,1"])   return @"iPod Touch 4G (A1367)";
    if ([platform isEqualToString:@"iPod5,1"])   return @"iPod Touch 5G (A1421/A1509)";
    
    if ([platform isEqualToString:@"iPad1,1"])   return @"iPad 1G (A1219/A1337)";
    
    if ([platform isEqualToString:@"iPad2,1"])   return @"iPad 2 (A1395)";
    if ([platform isEqualToString:@"iPad2,2"])   return @"iPad 2 (A1396)";
    if ([platform isEqualToString:@"iPad2,3"])   return @"iPad 2 (A1397)";
    if ([platform isEqualToString:@"iPad2,4"])   return @"iPad 2 (A1395+New Chip)";
    if ([platform isEqualToString:@"iPad2,5"])   return @"iPad Mini 1G (A1432)";
    if ([platform isEqualToString:@"iPad2,6"])   return @"iPad Mini 1G (A1454)";
    if ([platform isEqualToString:@"iPad2,7"])   return @"iPad Mini 1G (A1455)";
    
    if ([platform isEqualToString:@"iPad3,1"])   return @"iPad 3 (A1416)";
    if ([platform isEqualToString:@"iPad3,2"])   return @"iPad 3 (A1403)";
    if ([platform isEqualToString:@"iPad3,3"])   return @"iPad 3 (A1430)";
    if ([platform isEqualToString:@"iPad3,4"])   return @"iPad 4 (A1458)";
    if ([platform isEqualToString:@"iPad3,5"])   return @"iPad 4 (A1459)";
    if ([platform isEqualToString:@"iPad3,6"])   return @"iPad 4 (A1460)";
    
    if ([platform isEqualToString:@"iPad4,1"])   return @"iPad Air (A1474)";
    if ([platform isEqualToString:@"iPad4,2"])   return @"iPad Air (A1475)";
    if ([platform isEqualToString:@"iPad4,3"])   return @"iPad Air (A1476)";
    if ([platform isEqualToString:@"iPad4,4"])   return @"iPad Mini 2G (A1489)";
    if ([platform isEqualToString:@"iPad4,5"])   return @"iPad Mini 2G (A1490)";
    if ([platform isEqualToString:@"iPad4,6"])   return @"iPad Mini 2G (A1491)";
    
    if ([platform isEqualToString:@"i386"])      return @"iPhone Simulator";
    if ([platform isEqualToString:@"x86_64"])    return @"iPhone Simulator";
    
    return platform;
}

#pragma mark - UI

+ (UIView *)generateBadgeLabel:(NSInteger)number colorful:(BOOL)colorful {
    if (number <= 0)  return nil;
    
    UILabel *badgeNumber = [[UILabel alloc] init];
    [badgeNumber setOpaque:YES];
    if (colorful) {
        [badgeNumber setText:[NSString stringWithFormat:@"%@", @(number)]];
        [badgeNumber setBackgroundColor:COLOR_YELLOW];
        [badgeNumber setHighlightedTextColor:COLOR_YELLOW];
        [badgeNumber setTextColor:[UIColor whiteColor]];
    } else {
        [badgeNumber setText:[NSString stringWithFormat:@"( %@ )", @(number)]];
        [badgeNumber setTextColor:COLOR_NORMAL_SUB_INFOR];
        badgeNumber.backgroundColor = [UIColor clearColor];
        
    }
    
    [badgeNumber setFont:[TKFont systemFontOfSize:12.0f]];
    [badgeNumber sizeToFit];
    [badgeNumber setTextAlignment:NSTextAlignmentCenter];
    [badgeNumber setFrame:CGRectMake(0, 0, badgeNumber.frame.size.width + 10, badgeNumber.frame.size.height)];
    [badgeNumber.layer setCornerRadius:badgeNumber.frame.size.height / 2];
    if (colorful) {
        [badgeNumber setCenter:CGPointMake(kScreenWidth - 65 - badgeNumber.frame.size.width / 2, 22)];
    } else {
        [badgeNumber setCenter:CGPointMake(55 + badgeNumber.frame.size.width / 2, 22)];
    }
    
    [badgeNumber.layer setMasksToBounds:YES];
    return badgeNumber;
}

+ (SegmentedControl *)createViewContent:(NSArray *)configureData titleColor:(UIColor *)titleColor {
    SegmentedControl *segControl = [[SegmentedControl alloc] initWithTitles:[configureData valueForKey:@"title"] andVerSpace:1.0];
    segControl.layer.cornerRadius = 5;
    segControl.clipsToBounds = YES;
    segControl.layer.borderWidth = 1.0;
    segControl.layer.borderColor =  titleColor.CGColor;
    segControl.titleColor = titleColor;
    segControl.selectedTitleColor = [UIColor whiteColor];
    segControl.selectedFlow = NO;
    segControl.separatorHidden = YES;
    segControl.shadowPosition = SegmentedControlShadowPositionNone;
    NSArray *btns = segControl.buttons;
    for (UIButton *btn in btns) {
        [btn setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageWithColor:titleColor] forState:UIControlStateDisabled];
    }
    segControl.titleFont = [TKFont systemFontOfSize:14];
    segControl.selectedFlow = NO;
    return segControl;
}

+ (BOOL)canHandlePush {
    BOOL canHandle = YES;
    
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(currentUserNotificationSettings)]) {
        UIUserNotificationSettings *settings = [[UIApplication sharedApplication] currentUserNotificationSettings];
        if (settings.types == UIUserNotificationTypeNone) {
            canHandle = NO;
        }
    }
    DLog(@"canhandle : %@, another bool:%@", @(canHandle), @([UIApplication sharedApplication].applicationState != UIApplicationStateActive));
    return canHandle || [UIApplication sharedApplication].applicationState != UIApplicationStateActive;
}

+ (BOOL)isDate:(NSDate *)date1 sameDayToDate:(NSDate *)date2 format:(NSString *)format {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:format];
    NSString *dayVString = [formatter stringFromDate:date1];
    NSString *focusDayString = [formatter stringFromDate:date2];
    return [dayVString isEqualToString:focusDayString];
}

+ (void)openURL:(NSURL *)url {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        [[UIApplication sharedApplication] openURL:url];
    });
}

+ (NSArray *)calsInvalidDaysForYear:(int)year month:(int)month day:(int)day {
    int fixedDays = 31;
    
    NSMutableArray *months = [@[@31,@0,@31,@30,@31,@30,@31,@31,@30,@31,@30,@31,@31,@0,@31,@30,@31,@30,@31,@31,@30,@31,@30,@31,@31] mutableCopy];
    
    months[1] = (((year%4 == 0)&&(year%100 != 0)) || (year%400 == 0)) ? @29 : @28;
    year += 1;
    months[13] = (((year%4 == 0)&&(year%100 != 0)) || (year%400 == 0)) ? @29 : @28;
    
    NSMutableArray *invalidDays = [NSMutableArray array];
    
    //
    for (int i = 1; i <= 12; i++) {
        int tmpMonth = month + 1;
        NSInteger maxDay = [months[tmpMonth - 1] integerValue];
        NSInteger curMaxDay = [months[month - 1] integerValue];
        
        NSInteger validDays = (curMaxDay - day + 1 + maxDay);
        if (day > maxDay) {
            day = 1;
            month = tmpMonth + 1;
        } else {
            validDays = (curMaxDay - day + 1 + day - 1);
            month = tmpMonth;
        }
        
        for (NSInteger j = validDays + 1; j <= fixedDays; j++) {
            [invalidDays addObject:@((i - 1) * fixedDays + j - 1)];
        }
        
    }
    
    return invalidDays;
}


+ (CGFloat)getTheProportionNewSpaceWithScreenWidth:(CGFloat)space{
    return  ceilf(space *kScreenWidth/375.);
}

+ (NSString *)dataNetworkTypeFromStatusBar {
    UIApplication *app = [UIApplication sharedApplication];
    NSArray *subviews = [[[app valueForKey:@"statusBar"] valueForKey:@"foregroundView"] subviews];
    NSNumber *dataNetworkItemView = nil;
    for (id subview in subviews) {
        if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]){
            dataNetworkItemView = subview;
            break;
        }
    }
    
    NSNumber * num = [dataNetworkItemView valueForKey:@"dataNetworkType"];
    if (num == nil) {
        return @"NONE";
    } else {
        int n = [num intValue];
        if (n == 0) {
            return @"UNKNOWN";
        } else if (n == 1) {
            return @"CELL_2G";
        } else if (n == 2) {
            return @"CELL_3G";
        } else if (n == 3) {
            return @"CELL_4G";
        } else {
            return @"WIFI";
        }
    }
}

+ (UIImage *)captureWholeScrollViewContentWithScreenScale:(CGFloat)scale compressionQuality:(CGFloat)quality isOpaque:(BOOL)opaque scrollView:(UIScrollView *)scrollView {
    UIImage *image = nil;
    UIGraphicsBeginImageContextWithOptions(scrollView.contentSize, opaque, scale);
    {
        CGPoint oldContentOffset = scrollView.contentOffset;
        CGRect oldFrame = scrollView.frame;
        scrollView.contentOffset = CGPointZero;
        scrollView.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height);
        
        [scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];
        //        [scrollView drawViewHierarchyInRect:scrollView.bounds afterScreenUpdates:NO];
        image = UIGraphicsGetImageFromCurrentImageContext();
        
        scrollView.contentOffset = oldContentOffset;
        scrollView.frame = oldFrame;
    }
    UIGraphicsEndImageContext();
    
    if (image) {
        NSData *imageData = UIImageJPEGRepresentation(image, quality);
        image = [UIImage imageWithData:imageData];
    }
    return image;
}

+ (UIImage *)getverticalMontageWithImages:(NSArray<UIImage*> *)images cutTopHeight:(CGFloat)cutTopHeight {
    UIImage *image = nil;
    CGFloat imageWidth = kScreenWidth;
    CGFloat imageHeight = 0.0;//累加所有图片的总高 / 非第一张图片的Y值
    NSMutableArray *frameArray = [NSMutableArray arrayWithCapacity:0];
    
    for (UIImage *subImg in images) {
        CGSize size = subImg.size;
        CGFloat scale = size.width/imageWidth;
        NSValue *imgFrameValue = [NSValue valueWithCGRect:CGRectMake(0, imageHeight - cutTopHeight, imageWidth, size.height/scale)];
        [frameArray safeAddObject:imgFrameValue];
        imageHeight += size.height/scale;
    }
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(imageWidth, imageHeight - cutTopHeight), NO, [UIScreen mainScreen].scale);
    {
        for (NSUInteger i = 0; i<images.count; i++) {
            NSValue *frameValue = [frameArray safeObjectAtIndex:i];
            CGRect imgFrame = [frameValue CGRectValue];
            UIImage *image = [images safeObjectAtIndex:i];
            [image drawInRect:imgFrame];
        }
        image = UIGraphicsGetImageFromCurrentImageContext();
    }
    UIGraphicsEndImageContext();
    
    if (image) {
        NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
        image = [UIImage imageWithData:imageData];
    }
    return image;
}

+ (UIImage *)getverticalMontageWithImages:(NSArray<UIImage*> *)images cutBottomHeight:(CGFloat)cutBottomHeight {
    UIImage *image = nil;
    CGFloat imageWidth = kScreenWidth;
    CGFloat imageHeight = 0.0;//累加所有图片的总高 / 非第一张图片的Y值
    NSMutableArray *frameArray = [NSMutableArray arrayWithCapacity:0];
    
    for (UIImage *subImg in images) {
        CGSize size = subImg.size;
        CGFloat scale = size.width/imageWidth;
        NSValue *imgFrameValue = [NSValue valueWithCGRect:CGRectMake(0, imageHeight, imageWidth, size.height/scale)];
        [frameArray safeAddObject:imgFrameValue];
        imageHeight += size.height/scale;
    }
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(imageWidth, imageHeight - cutBottomHeight), NO, [UIScreen mainScreen].scale);
    {
        for (NSUInteger i = 0; i<images.count; i++) {
            NSValue *frameValue = [frameArray safeObjectAtIndex:i];
            CGRect imgFrame = [frameValue CGRectValue];
            UIImage *image = [images safeObjectAtIndex:i];
            [image drawInRect:imgFrame];
        }
        image = UIGraphicsGetImageFromCurrentImageContext();
    }
    UIGraphicsEndImageContext();
    
    if (image) {
        NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
        image = [UIImage imageWithData:imageData];
    }
    return image;
}

@end
